//
//  SFPNutrientIntakeModel.swift
//  StriveForPregnancy
//
//  Created by iOS-Czz on 2023/11/9.
//

import UIKit

class SFPNutrientIntakeViewModel{
    var dataSource = [SFPNutrientIntakeModel]()
    var carcount = 0
    var procount = 0
    var fatcount = 0
}
extension SFPNutrientIntakeViewModel{
    func loadData(_ date:String ,onSuccess: ((_ models: [SFPNutrientIntakeModel]) ->Void)?){
        let dataHelper = SFPNutrientIntakeModel.getUsingLKDBHelper()
        let sql = "select * from @t where date = '\(date)'"
        let modelArr = dataHelper.search(withSQL: sql, to: SFPNutrientIntakeModel.self) as! [SFPNutrientIntakeModel]
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "yyyy.MM.dd"
        let sortedModels = modelArr.sorted { (model1, model2) -> Bool in
            guard let date1 = dateFormatter.date(from: model1.date),
                  let date2 = dateFormatter.date(from: model2.date) else {
                return false // 如果转换失败则直接返回 false
            }
            return date1 < date2
        }
        carcount = sortedModels.filter { $0.type == 0 }.reduce(0) { $0 + $1.intake }
        procount = sortedModels.filter { $0.type == 1 }.reduce(0) { $0 + $1.intake }
        fatcount = sortedModels.filter { $0.type == 2 }.reduce(0) { $0 + $1.intake }
        self.dataSource = sortedModels
        onSuccess?(self.dataSource)
    }
    
}

@objcMembers
class SFPNutrientIntakeModel: SFPModel,Codable {
    var name = ""
    var type = 0
    var intake = 0
    var date = ""
    var isDefault = true
    override class func getTableName() -> String {
        return  String(describing: SFPNutrientIntakeModel.self)
    }
}
